package edu.sctu.yueding.activitys;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.HashMap;

import edu.sctu.yueding.R;
import edu.sctu.yueding.adapter.SignUpMyTeamAdapter;
import edu.sctu.yueding.alipay.PayActivity;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.JsonBaseListBean;
import edu.sctu.yueding.bean.MyTeamMembersBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.L;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.CustomDialog;

/**
 * Created by fll on 2016/8/3.
 */
public class SignUpMyTeamActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mBackButton, mAddMemberButton;
    private Button mFinishSignInButton;
    private ListView mListView;
    private SignUpMyTeamAdapter adapter = null;
    private int i = 0;

//    private int lineMembersCount;

    private int lineMembersMinCount;

    private int lineMembersMaxCount;

    private JsonBaseListBean<MyTeamMembersBean> myTeamMembersBean;

    private ProgressUtil progressUtil;
    private ProgressDialog progressDialog;
    private SharePreference sharePreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_up_my_team);

        initView();
        initSystemBar(this, 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setMemberInfoDataChange();
    }

    private void initView() {

        sharePreference = SharePreference.getInstance(SignUpMyTeamActivity.this);


//        lineMembersCount = SharePreference.getInstance(this).getInt(CacheConfig.CACHE_LINE_NUMBER);

        lineMembersMinCount = SharePreference.getInstance(this).getInt(CacheConfig.CACHE_LINE_MIN_NUMBER);

        lineMembersMaxCount = SharePreference.getInstance(this).getInt(CacheConfig.CACHE_LINE_MAX_NUMBER);

        progressUtil = ProgressUtil.getInstance(this, "");

        mBackButton = (ImageView) findViewById(R.id.sign_up_my_team_back_button);
        mAddMemberButton = (ImageView) findViewById(R.id.sign_up_my_team_add_button);
        mFinishSignInButton = (Button) findViewById(R.id.sign_up_my_team_finish_button);
        mListView = (ListView) findViewById(R.id.sign_up_my_team_listview);

        mBackButton.setOnClickListener(this);
        mAddMemberButton.setOnClickListener(this);
        mFinishSignInButton.setOnClickListener(this);
        i = i + 1;
    }

    /**
     * 往list里添加数据，设置适配器
     */
    private void setMemberInfoDataChange() {

        progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_SPINNER, false);

        GetVolleyHttp.getInstance(this).getStringGETJsonData(URLConfig.getMyTeamMember(sharePreference.getInt(CacheConfig.CACHE_TEAM_ID)),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        progressUtil.dismiss(progressDialog);

//                        myTeamMembersBean = JSON.parseObject(response,MyTeamMembersBean.class);
                        myTeamMembersBean = JSON.parseObject(response, new TypeReference<JsonBaseListBean<MyTeamMembersBean>>() {
                        }.getType());

                        if (adapter == null) {
                            adapter = new SignUpMyTeamAdapter(SignUpMyTeamActivity.this, myTeamMembersBean.getData());
                            mListView.setAdapter(adapter);
                        } else {
                            adapter.fresh(myTeamMembersBean.getData(), false);
                        }

                        L.d("addMembers", "sssssss");

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressUtil.dismiss(progressDialog);
                        Toast.makeText(SignUpMyTeamActivity.this, "网络出了点问题", Toast.LENGTH_SHORT).show();
                        L.d("addMembers", "fffff");
                    }
                }, "");


//        if (!myTeamMemberBeen.getRealName().equals("")) {
//
//            myTeamMemberBeenList.add(myTeamMemberBeen);
//
//            if (adapter == null) {
//                adapter = new SignUpMyTeamAdapter(this, myTeamMemberBeenList);
//                mListView.setAdapter(adapter);
//            } else {
//                adapter.onDateChange(myTeamMemberBeenList);
//            }
//        }
    }

//    private MyTeamMemberBean setMemberInfoByCache() {
//        MyTeamMemberBean myTeamMemberBeen = new MyTeamMemberBean();
//
//        sharePreference = SharePreference.getInstance(this);
//        myTeamMemberBeen.setRealName(sharePreference.getString(CacheConfig.CACHE_ADD_MEMBER_REAL_NAME));
//        myTeamMemberBeen.setGender(sharePreference.getString(CacheConfig.CACHE_ADD_MEMBER_SEX));
//        myTeamMemberBeen.setIdNumber(sharePreference.getString(CacheConfig.CACHE_ADD_MEMBER_ID_CARD));
//        myTeamMemberBeen.setPhoneNumber(sharePreference.getString(CacheConfig.CACHE_ADD_MEMBER_PHONE));
//
//        return myTeamMemberBeen;
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_up_my_team_back_button:
//                removeCache();
                JumpUtils.jumpActivity(this, ChooseLineActivity.class);
                finish();
                break;
            case R.id.sign_up_my_team_add_button:


                if (lineMembersMinCount == lineMembersMaxCount) {

                    if (myTeamMembersBean != null && myTeamMembersBean.getData().size() < lineMembersMinCount) {
                        JumpUtils.jumpActivity(SignUpMyTeamActivity.this, SignUpAddMemberActivity.class);
                    } else {
                        Toast.makeText(SignUpMyTeamActivity.this, "每个团队只能添加" + lineMembersMaxCount + "个成员", Toast.LENGTH_SHORT)
                                .show();
                    }

                } else {

                    if (myTeamMembersBean != null && myTeamMembersBean.getData().size() < lineMembersMaxCount) {
                        JumpUtils.jumpActivity(SignUpMyTeamActivity.this, SignUpAddMemberActivity.class);
                    } else {
                        Toast.makeText(SignUpMyTeamActivity.this, "只能添加" + lineMembersMinCount + "到" + lineMembersMaxCount + "个成员", Toast.LENGTH_SHORT)
                                .show();
                    }

                }
                break;
            case R.id.sign_up_my_team_finish_button:

                if (lineMembersMinCount == lineMembersMaxCount) {

                    if (myTeamMembersBean.getData().size() == lineMembersMaxCount) {

                        jumpPay();


                    } else {

                        Toast.makeText(SignUpMyTeamActivity.this, "请添加" + lineMembersMaxCount + "名参赛者！", Toast.LENGTH_SHORT).show();
                    }

                } else {

                    if (myTeamMembersBean.getData().size() >= lineMembersMinCount && myTeamMembersBean.getData().size() <= lineMembersMaxCount) {

                        jumpPay();

                    } else {

                        Toast.makeText(SignUpMyTeamActivity.this, "请添加" + lineMembersMinCount + "到" + lineMembersMaxCount + "个成员", Toast.LENGTH_SHORT).show();
                    }


                }


//                removeCache();

                break;
        }
    }

    private void jumpPay() {
        if (sharePreference.getBoolean(CacheConfig.IS_PRICE)) {

            finishEnroll();

        } else {

            Bundle bundle = new Bundle();
            bundle.putBoolean("payAgain", false);
            JumpUtils.jumpActivity(SignUpMyTeamActivity.this, PayActivity.class, bundle);
            finish();
        }
    }

    private void finishEnroll() {

        HashMap<String, String> map = new HashMap<>();
        String matchId = sharePreference.getString(CacheConfig.CACHE_MATCH_ID);
        Long routeId = sharePreference.getLong(CacheConfig.CACHE_ROUTE_ID);
        String teamId = String.valueOf(sharePreference.getInt(CacheConfig.CACHE_TEAM_ID));

        map.put("matchId", String.valueOf(matchId));
        map.put("routeId", String.valueOf(routeId));
        map.put("teamId", teamId);

        progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_SPINNER, false);

        GetVolleyHttp.getInstance(this).getStringPOSTJsonData(URLConfig.MY_SIGN, map,

                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        progressUtil.dismiss(progressDialog);

                        JsonBaseBeen<String> json = JSON.parseObject(response, new TypeReference<JsonBaseBeen<String>>() {
                        }.getType());

                        if (json.getMeta().code == 200) {

                            finishDialog();

                        } else if (json.getMeta().code == 40000701) {
                            Toast.makeText(SignUpMyTeamActivity.this, "团队人数错误", Toast.LENGTH_SHORT).show();

                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressUtil.dismiss(progressDialog);
                        Toast.makeText(SignUpMyTeamActivity.this, "网络出了点问题", Toast.LENGTH_SHORT).show();
                    }
                }, "");

    }


    public void finishDialog() {

        final CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessage("提示：报名成功，可通过个人中心查看！");
        builder.setPositiveButton("立即查看", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
//                JumpUtils.jumpActivity(PayActivity.this, MyOrderListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("flag", 3);
                JumpUtils.activityToFragmentJump(SignUpMyTeamActivity.this, bundle);
                SharePreference.getInstance(SignUpMyTeamActivity.this).removeOneCache(CacheConfig.CACHE_LINE_MIN_NUMBER);
                SharePreference.getInstance(SignUpMyTeamActivity.this).removeOneCache(CacheConfig.CACHE_LINE_MAX_NUMBER);
                finish();
            }
        });
        builder.create().show();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
//            removeCache();
            JumpUtils.jumpActivity(this, ChooseLineActivity.class);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    private void removeCache() {
//        sharePreference = SharePreference.getInstance(this);
//        sharePreference.removeOneCache(CacheConfig.CACHE_ADD_MEMBER_REAL_NAME);
//        sharePreference.removeOneCache(CacheConfig.CACHE_ADD_MEMBER_PHONE);
//        sharePreference.removeOneCache(CacheConfig.CACHE_ADD_MEMBER_SEX);
//        sharePreference.removeOneCache(CacheConfig.CACHE_ADD_MEMBER_ID_CARD);
//    }
}
